package com.techsoul.module.order.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.poi.ExcelExport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.order.mapper.PriceTrackMapper;
import com.techsoul.module.order.pojo.entity.PriceTrack;
import com.techsoul.module.order.pojo.param.PriceTrackSaveParam;
import com.techsoul.module.order.pojo.param.PriceTrackSearchParam;
import com.techsoul.module.order.pojo.vo.PriceTrackVo;
import com.techsoul.module.order.service.IPriceTrackService;
import com.techsoul.module.system.service.IConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户地址 Service实现
 * 
 * @author liuen
 * @date 2021-04-06
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class PriceTrackServiceImpl implements IPriceTrackService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private PriceTrackMapper mapper;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private IConfigService configService;
    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(PriceTrackSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        PriceTrack entity = new PriceTrack();
        BeanUtils.copyProperties(params, entity);
        entity.setUserId(user.getId())
                .setId(idWorker.nextId() + "")
                .preInsert(user.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(PriceTrackSaveParam params) {
        PriceTrack entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 更新用户默认地址
     * @param params
     */
    @Override
    public void updateDefaultAddress(PriceTrackSaveParam params) {
        if (ApiConstants.Y.equals(params.getIsDefault())) {
            this.mapper.updateIsDefault(params.getUserId(), ApiConstants.N);
        }
        if (ApiConstants.N.equals(params.getIsDefault())) {
            this.mapper.updateIsDefault(params.getUserId(), ApiConstants.Y);
        }
        this.update(params);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public PriceTrackVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 获取用户默认收货地址
     * @return
     */
    @Override
    public PriceTrackVo findDefaultAddress() {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        return this.mapper.findDefaultAddress(user.getId());
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<PriceTrackVo> findAll(PriceTrackSearchParam params) {
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<PriceTrackVo> findAll(PriceTrackSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

    /**
     * 用户收货地址列表
     * @return
     */
    @Override
    public List<PriceTrackVo> findMyAddressList() {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        PriceTrackSearchParam params = new PriceTrackSearchParam();
        params.setUserId(user.getId());
        return this.findAll(params);
    }
    @Override
    public String exportTrackData(PriceTrackSearchParam params) {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "价格监控报告-"+params.getCreateTimeBegin().replace("-", "")+ "-"+ DateUtils.getDate("yyyyMMdd")+".xlsx";

        List<PriceTrackVo> list = this.mapper.findAll(params);
        try {
            new ExcelExport(null, PriceTrackVo.class).setDataList(list).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("结算清单", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }
}
